/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> neighbors;
    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }
    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }
    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
*/

class Solution {
public:
    Node* cloneGraph(Node* node) {
        if (node == nullptr)
            return node;

        unordered_map<Node*, Node*> vis;
        queue<Node*> q;
        q.push(node);
        vis[node] = new Node(node->val);
        while (!q.empty())
        {
            auto n = q.front(); // 取出头节点
            q.pop();
            for (auto& neighbor: n->neighbors) // 遍历节点的邻居
            {
                if (vis.find(neighbor) == vis.end()) // 如果没有被访问过，就克隆并存储在哈希表中
                {
                    vis[neighbor] = new Node(neighbor->val);
                    q.push(neighbor); // 将邻居节点加入队列中
                }
                vis[n]->neighbors.push_back(vis[neighbor]); // 更新当前节点的邻居列表
            }
        }
        return vis[node];
    }
};